package com.wbs.service.error;

import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.wbs.service.canonical.ErrorResponseBean;


/**Class where exceptions are declared*/
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    /** Exception that represent InvalidRequestException information */
    @ExceptionHandler({ InvalidRequestException.class })
    public ResponseEntity<Object> handleInvalidRequest(final RuntimeException ex, final WebRequest request){

        InvalidRequestException irEx = (InvalidRequestException)ex;
        ErrorResponseBean errorResponseBean = irEx.getErrorResponseBean();

        return handleExceptionInternal(ex, errorResponseBean, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
    }

    /** Handle database exceptions */
    @ExceptionHandler({ DataAccessException.class })
    public ResponseEntity<Object> handleDataAccessException(final RuntimeException ex, final WebRequest request){
        InvalidRequestException invalidRequestException = new InvalidRequestException("An error occurred during the transaction");
        ErrorResponseBean errorResponseBean = invalidRequestException.getErrorResponseBean();

        return handleExceptionInternal(ex, errorResponseBean, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
    }

    /** Exception that represent DuplicateValueException information */
    @ExceptionHandler({ DuplicateValueException.class})
    public ResponseEntity<Object> handleDuplicateValue(final RuntimeException ex, final WebRequest request){
        
        DuplicateValueException irEx = (DuplicateValueException)ex;
        ErrorResponseBean errorResponseBean = irEx.getErrorResponseBean();
        
        return handleExceptionInternal(ex, errorResponseBean, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
    }

    /** Exception that represent handleInternalException information */
    @ExceptionHandler({ NullPointerException.class, IllegalArgumentException.class, IllegalStateException.class})
    public ResponseEntity<Object> handleInternal(final RuntimeException ex, final WebRequest request){
        final String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
    }

}